//
//  LSWorkDayReportDetailViewController.m
//  LaSaCivilAffairsDepartment
//
//  Created by 聂志康 on 2019/1/24.
//  Copyright © 2019 wpkj. All rights reserved.
//

#import "LSWorkDayReportDetailViewController.h"

@interface LSWorkDayReportDetailViewController () <UITextViewDelegate>
@property (nonatomic, strong) UIView *footerView;
@end

@implementation LSWorkDayReportDetailViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager]; // 获取类库的单例变量
    keyboardManager.enable = NO; // 控制整个功能是否启用
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager]; // 获取类库的单例变量
    keyboardManager.enable = YES; // 控制整个功能是否启用
}

//当键盘出现
- (void)keyboardWillShow:(NSNotification *)notification {
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    int height = keyboardRect.size.height;
    [UIView animateWithDuration:0.25 animations:^{
        self.contentTV.frame = CGRectMake(15, 15, ScreenWidth-30, ScreenHeight-SafeAreaTopHeight-100-height+20);
        self.footerView.frame = CGRectMake(0, ScreenHeight-SafeAreaTopHeight-100-height+20, ScreenWidth, 100);
    }];
}

//当键退出
- (void)keyboardWillHide:(NSNotification *)notification {
    [UIView animateWithDuration:0.25 animations:^{
        self.contentTV.frame = CGRectMake(15, 15, ScreenWidth-30, ScreenHeight-SafeAreaTopHeight-SafeAreaBottomHeight-100-100);
        self.footerView.frame = CGRectMake(0, ScreenHeight-SafeAreaTopHeight-SafeAreaBottomHeight-100-100, ScreenWidth, 100);
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
#pragma mark - 键盘事件
    //监听当键盘将要出现时
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //监听当键将要退出时
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    [self.view addSubview:self.contentTV];
    if ([self.title rangeOfString:@"添加"].length > 0) {
        [self.view addSubview:self.footerView];
    } else {
        self.contentTV.editable = false;
        //获取当前时间日期
        NSDate *date=[NSDate date];
        NSDateFormatter *format1=[[NSDateFormatter alloc] init];
        [format1 setDateFormat:@"yyyy-MM-dd"];
        NSString *dateStr=[format1 stringFromDate:date];
        if (![[ValidateUtils validateNull:[UserInfoModel sharedInstance].customerRealName] isEqualToString:@""] && [[UserInfoModel sharedInstance].customerRealName isEqualToString:self.createName] && [dateStr isEqualToString:self.createDate]) {
            UIButton *editButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 44)];
            editButton.titleLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:14];
            [editButton setTitle:@"编辑" forState:UIControlStateNormal];
            [editButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
            [editButton addTarget:self action:@selector(editButtonClick) forControlEvents:UIControlEventTouchUpInside];
            UIBarButtonItem *editItem = [[UIBarButtonItem alloc] initWithCustomView:editButton];
            self.navigationItem.rightBarButtonItem = editItem;
        }
    }
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView {
    if (textView == self.contentTV && textView.text.length > 999) return FALSE;
    return TRUE;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    //判断加上输入的字符，是否超过界限specialityTF  experienceTF
    NSString *str = [NSString stringWithFormat:@"%@%@", textView.text, text];
    NSInteger MaxLength = 1000;
    if (str.length > MaxLength) {
        NSRange rangeIndex = [str rangeOfComposedCharacterSequenceAtIndex:MaxLength];
        if (rangeIndex.length == 1) {//字数超限
            textView.text = [str substringToIndex:MaxLength];
        }else{
            NSRange rangeRange = [str rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, MaxLength)];
            textView.text = [str substringWithRange:rangeRange];
        }
        return NO;
    }
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView {
    if (textView.text.length > 999) textView.text = [textView.text substringToIndex:1000];
}

- (void)editButtonClick {
    self.navigationItem.rightBarButtonItem = nil;
    self.contentTV.editable = true;
    [self.contentTV becomeFirstResponder];
    [self.view addSubview:self.footerView];
}

#pragma mark - 提交按钮点击事件
- (void)submitButtonClick {
    if ([self.contentTV.text isEqualToString:@""]) {
        [MBProgressHUD showTipMessageInWindow:@"您未输入任何内容"];
        return;
    }
    NSDateFormatter *formatter = [TimeUtils getFormat5];
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    if ([self.title rangeOfString:@"添加"].length > 0) {
        NSDictionary *param = @{@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token],@"time":currentTimeString,@"context":[ValidateUtils disable_emoji:self.contentTV.text]};
        [NetworkUtils requestNOHandleWithMethod:@"POST" URL:WorkReportAdd param:param completionHandler:^(id responseObject, NSError *connectionError) {
            if (!connectionError) {
                [MBProgressHUD showTipMessageInWindow:responseObject[@"message"]];
                NSNumber *status = [responseObject objectForKey:@"status"];
                if (status.integerValue == 200) {
                    WS
                    if (self.refreshBlock) self.refreshBlock();
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [weakSelf.navigationController popViewControllerAnimated:true];
                    });
                }
            } else {
                [MBProgressHUD showTipMessageInWindow:connectionError.localizedDescription];
            }
        }];
    } else {
        NSDictionary *param = @{@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token],@"time":currentTimeString,@"context":self.contentTV.text,@"id":self.workDayReportId};
        [NetworkUtils requestNOHandleWithMethod:@"POST" URL:WorkReportEdit param:param completionHandler:^(id responseObject, NSError *connectionError) {
            if (!connectionError) {
                [MBProgressHUD showTipMessageInWindow:responseObject[@"message"]];
                NSNumber *status = [responseObject objectForKey:@"status"];
                if (status.integerValue == 200) {
                    WS
                    if (self.refreshBlock) self.refreshBlock();
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [weakSelf.navigationController popViewControllerAnimated:true];
                    });
                }
            } else {
                [MBProgressHUD showTipMessageInWindow:connectionError.localizedDescription];
            }
        }];
    }
}

- (UITextView *)contentTV {
    if (!_contentTV) {
        _contentTV = [[UITextView alloc] initWithFrame:CGRectMake(15, 15, ScreenWidth-30, ScreenHeight-SafeAreaTopHeight-SafeAreaBottomHeight-100-100)];
        _contentTV.layer.cornerRadius = 5;
        _contentTV.layer.masksToBounds = true;
        _contentTV.layer.borderColor = hexColor(dbdbdb).CGColor;
        _contentTV.layer.borderWidth = 1;
        _contentTV.delegate = self;
    }
    return _contentTV;
}

- (UIView *)footerView {
    if (!_footerView) {
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenHeight-SafeAreaTopHeight-SafeAreaBottomHeight-100-100, ScreenWidth, 100)];
        UIButton *submitButton = [[UIButton alloc] initWithFrame:CGRectMake(15, 30, ScreenWidth-30, 40)];
        [submitButton setTitle:@"提交" forState:UIControlStateNormal];
        [submitButton setTitleColor:hexColor(ffffff) forState:UIControlStateNormal];
        submitButton.titleLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:14];
        submitButton.backgroundColor = hexColor(FDBB2C);
        submitButton.layer.cornerRadius = 4;
        submitButton.layer.masksToBounds = true;
        [submitButton addTarget:self action:@selector(submitButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [_footerView addSubview:submitButton];
    }
    return _footerView;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
